<template>
    <div class="center">
        <div class="center-form">
          <el-form inline label-width="120px" @submit.native.prevent>
            <el-form-item label="商户名称">
              <el-input v-model="listParsem.merchantName" placeholder="请输入商户名称" clearable class="selWidth" size="small" />
            </el-form-item>
            <el-form-item label="门店名称">
              <el-input v-model="listParsem.shopName" placeholder="请输入门店名称" clearable class="selWidth" size="small" />
            </el-form-item>
            <el-form-item label=" ">
              <el-button
                icon="el-icon-search"
                type="primary"
                @click="initGetList"
                >搜索</el-button
              >
              <el-button icon="el-icon-refresh" type="primary" @click="resetList"
                >重置</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div class="center-construct">
            <el-button type="primary" style="margin-right: 30px;" @click="addBannerdialogClick">新增Banner</el-button>
        </div>
        <div class="center-table">
            <el-table
          :data="tableList"
          tooltip-effect="dark"
          style="width: 100%"
          stripe
          :header-cell-style="tableHeaderColor"
        >
        <el-table-column
            prop="merchantName"
            label="商户名称"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="merchantAppId"
            label="商户id"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="shopName"
            label="门店名称"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="cycleShopId"
            label="门店id"
            align="center"
          ></el-table-column>
          <el-table-column
            label="图片"
            align="center"
            width="250"
          >
          <template slot-scope="scope">
              <el-image 
                style="width: 100px; height: 100px"
                :src="scope.row.bannerUrlList.split(',')[0]" 
                :preview-src-list="scope.row.bannerUrlList.split(',')">
              </el-image>
          </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            align="center"
          />
          <el-table-column
            fixed="right"
            align="center"
            label="操作"
            width="120"
          >
            <template slot-scope="scope">
                <el-button
                type="text"
                @click="deleteBanner(scope.row)"
                >编辑</el-button>
                <el-button
                v-if="!scope.row.plantActivityId"
                type="text"
                @click="redCardsBanner(scope.row)"
                >绑定红包</el-button>
                <el-popconfirm
                v-else
                    title="是否确认解绑？"
                    @confirm="redCardsClose(scope.row)"
                    >
                     <el-button
                     style="margin-left: 10px;"
                     slot="reference"
                      type="text"
                      >解绑红包</el-button>
                  </el-popconfirm>
               
              <!-- <el-button
                type="text"
                @click="checkInfo(scope.row)"
                >查看</el-button
              > -->
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
        <el-pagination
          background
          @current-change="handleCurrentChange"
          @size-change="sizechange"
          :page-size="listParsem.size"
          :current-page.sync="listParsem.page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
   </div>
   <el-dialog
         :title="constructForm.id? '编辑Banner' :'新增Banner'"
         :visible.sync="constructVisible"
         width="600px"
         :before-close="handleClose">
         <div v-if="constructVisible">
            <el-form :model="constructForm" :rules="constructFormRules" ref="ruleForm" label-width="100px" >
                <!-- <el-form-item label="商户id" prop="merchantAppId">
                   <el-input v-model="constructForm.merchantAppId" placeholder="请输入商户id"></el-input>
               </el-form-item> -->
               <!-- merchantName -->
               <el-form-item label="商户名称" >
                <el-select :disabled="constructForm.id" style="width: 400px;"  @change="merchantChange" v-model="constructForm.merchantAppId"  filterable placeholder="请选择商户" >
                    <el-option
                      v-for="item in merchantList"
                      :key="item.merchantPid"
                      :label="item.merchantName"
                      :value="item.merchantPid">
                    </el-option>
                  </el-select>
                   <!-- <el-input v-model="constructForm.merchantName" placeholder="请输入商户名称"></el-input> -->
               </el-form-item>
               <!-- <el-form-item label="门店id" prop="cycleShopId">
                   <el-input v-model="constructForm.cycleShopId" placeholder="请输入门店id"></el-input>
               </el-form-item> -->
               <el-form-item label="门店名称" prop="cycleShopId">
                <el-select :disabled="constructForm.id" style="width: 400px;"  @change="storeChange"  v-model="constructForm.cycleShopId"  filterable placeholder="请选择门店" >
                    <el-option
                      v-for="item in storeList"
                      :key="item.shopId"
                      :label="item.shopName"
                      :value="item.shopId">
                    </el-option>
                  </el-select>
                   <!-- <el-input v-model="constructForm.shopName" placeholder="请输入门店名称"></el-input> -->
               </el-form-item>
               <el-form-item label="banner图片" prop="bannerUrlList">
                <el-upload
                :action="uploadUrl"
                :headers="token"
                :limit="5"
                list-type="picture-card"
                :before-upload="beforeImageUpload"
                :on-success="bannerUpLoadSuccess"
                :file-list="bannerImageList"
                :on-remove="bannerUpLoadRemove">
                <i class="el-icon-plus"></i>
              </el-upload>
               </el-form-item>
               <el-form-item label="视频" prop="bannerUrlList">
                <el-upload
                v-loading="videoLoading"
                element-loading-text="上传中"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.8)"
                :action="uploadUrls"
                :headers="token"
                :before-upload="beforeVideoUpload"
                :on-success="bannervaildSuccess"
                :on-error="errorVideoUpload"
                :show-file-list="false"
               >
               <div v-if="bannervideoUrl">
                <video  autoplay controls  width="160" height="160" :src="bannervideoUrl"></video>
               </div>
                <i class="el-icon-plus" v-else></i>
              </el-upload>
               </el-form-item>
            </el-form>
         </div>
         <span slot="footer" class="dialog-footer">
           <el-button @click="handleClose">取 消</el-button>
           <el-button type="primary" @click="addBannerClick">确 定</el-button>
         </span>
       </el-dialog>
       <el-dialog
         title="红包绑定"
         :visible.sync="synVisible"
         width="470px"
         >
         <div>
            <el-form
            :model="systemFrom"
            ref="systemFrom"
            label-width="100px"
            >
              <el-form-item label="任务红包" prop="name" :rules="[ { required: true, message: '请选择任务红包', trigger: 'change' }]">
                <el-autocomplete @select="shopSelect"  v-model.trim="systemFrom.name"  :fetch-suggestions="chantShopFetchlist" :debounce="300" style="width: 300px;"  placeholder="请输入任务名称进行查询" />
              </el-form-item> 
             </el-form>
           </div>
         <span slot="footer" class="dialog-footer">
              <el-button @click="synVisible = false">取 消</el-button>
              <el-button type="primary"   @click="synFromdingClick">确 定</el-button>
          </span>
       </el-dialog>
</div>
</template>
<script>
import { bindActivity , planetQueryPage , shopQueryList , simpleCreateQuery , cycleBannerAdd , cydeBannerPage , cycleBannerEdit } from '@/api/fetchApi'
export default{
    data(){
        return{
            listParsem:{ page:1,size:10 },
            total:0,
            systemFrom:{
              name:''
            },
            synVisible:false,
            uploadUrls:process.env.VUE_APP_BASE_URL + "/product/v31/api/cycle/cycleBanner/uploadVideo",
            uploadUrl: process.env.VUE_APP_BASE_URL + "/product/v31/api/merchant/uploadfile/upload",
            token: { token: sessionStorage.getItem("token") },
            tableList:[],
            constructForm:{},
            constructVisible:false,
            constructFormRules:{
                merchantAppId:[{ required: true, message: '请输入商户id', trigger: 'blur' }],
                merchantName:[{ required: true, message: '请输入商户名称', trigger: 'blur' }],
                cycleShopId:[{ required: true, message: '请输入门店id', trigger: 'blur' }],
                shopName:[{ required: true, message: '请输入门店名称', trigger: 'blur' }],
                bannerUrlList:[{required: true, validator:(rule , value , callback)=>{
                    if(this.bannerImageList.length || this.bannervideoUrl){
                      console.log(this.bannerImageList.length ,  this.bannervideoUrl)
                        callback()
                    }else{
                        callback(new Error('请上传视频或者图片！'))
                    }
                 } }],
           },
           merchantList:[],
           storeList:[],
           bannerImageList:[],
           bannervideoUrl:'',
           bannerType:'',
           videoLoading:false
        }
    },
    mounted(){
       this.initGetList()  
       this.initStoreList()
       this.initSimpleCreateQuery()
    },
    methods:{
       async initGetList(){
           const res =  await cydeBannerPage(this.listParsem)
           res.data.forEach(item=>{
            item.bannerType =  item.bannerUrlList.substring(item.bannerUrlList.length - 3 , item.bannerUrlList.length)
           })
           this.tableList = res.data
           this.total = res.pageInfo.recordCount
        },
        addBannerdialogClick(){
            this.constructForm = {}
            this.bannervideoUrl = ''
            this.$nextTick(()=>{
              this.$refs.ruleForm.clearValidate()
            })
          this.constructVisible = true
        },
        async initSimpleCreateQuery(){
           this.merchantList = []
           const res =  await simpleCreateQuery({page:1,size:999999})
           this.total = res.pageInfo.recordCount
           res.data.forEach(item=>{
             this.merchantList.push(item.cycleMerchantDO)
          })
        },
        merchantChange(){
            this.initStoreList()
            this.constructForm.cycleShopId = ''
        },
        storeChange(v){
          this.constructForm.cycleShopId = v
          this.$forceUpdate()
        },
        async initStoreList(){
          this.storeList = []
          const res = await shopQueryList({page:1,size:999999,merchantPid:this.constructForm.merchantAppId})
          this.storeList = res.data
          console.log(this.storeList)
        },
       async addBannerClick(){
        this.constructForm.bannerUrlList = []
        if(this.bannerImageList.length >0){
          this.bannerImageList.forEach(item=>{
          this.constructForm.bannerUrlList.push(item.url)
        })
          this.constructForm.bannerUrlList =  this.constructForm.bannerUrlList.join(',')
        }else{
          this.constructForm.bannerUrlList =  this.bannervideoUrl
        }
          const valid = await  this.$refs.ruleForm.validate()
          if(valid){
            if(this.constructForm.merchantAppId){
              const data =  this.merchantList.find(item => item.merchantPid == this.constructForm.merchantAppId)
              this.constructForm.merchantName = data.merchantName
            }
             const storeData =  this.storeList.find(item => item.shopId == this.constructForm.cycleShopId)
             this.constructForm.shopName = storeData.shopName
            if(this.constructForm.id){
                const res = await cycleBannerEdit(this.constructForm)
                if(res.code == '200'){
                this.constructVisible = false
                this.$message.success(res.message)
                this.initGetList()  
             }else{
                this.constructVisible = false
                this.$message.error(res.message)
             }
            }else{
                const res = await cycleBannerAdd(this.constructForm)
             if(res.code == '200'){
                this.constructVisible = false
                this.$message.success(res.message)
                this.initGetList()  
             }else{
                this.constructVisible = false
                this.$message.error(res.message)
             }
            }
          }
        },
        chantShopFetchlist(queryString, cb) {
         let sosolist = {};
         sosolist = {
            pageNumber: 1,
            pageSize: 99,
            status:'ONGOING',
            tenantId:'tnt-231226dm6ojDSVEh8t9vbZqLdC3D'
           }
           planetQueryPage(sosolist).then(res => {
           // console.log(res);
           if (res.code == 405) {
             sessionStorage.removeItem("token");
             this.$router.push("/login");
           } else {
              let merchantarrlist = []
             for(var i=0;i<res.list.length;i++){
               merchantarrlist.push({'value':res.list[i].name,'id':res.list[i].plantActivityId})
             }
              let results = queryString
               ? merchantarrlist.filter(this.createFilter(queryString))
               : merchantarrlist
             // 调用 callback 返回建议列表的数据
             cb(results)
           }
         })
         },
         shopSelect(item) {
          // console.log(item)
          this.systemFrom.plantActivityId = item.id
          this.systemFrom.name = item.value
          this.$forceUpdate()
         },
         createFilter(queryString) {
           return restaurant => {
           return (
           restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1
           )
          }
        },
        logoRemove(){
          this.constructForm.bannerUrlList = ''
        },
        async synFromdingClick(){
          const valid = await  this.$refs.systemFrom.validate()
          if(valid){
            const res = await bindActivity(this.systemFrom)
          if(res.code == '200'){
                this.synVisible = false
                this.$message.success('绑定成功！')
                this.initGetList()  
          }else{
                this.synVisible = false
                this.$message.error(res.message)
                this.initGetList()  
          }
          }
          
        },
        bannerUpLoadSuccess(response, file, fileList){
            this.bannervideoUrl = ''
            fileList[fileList.length - 1] = {name:fileList[fileList.length - 1].name,url:fileList[fileList.length - 1].response.data.filePath}
            this.bannerImageList = fileList
        },
        bannervaildSuccess(response, file, fileList){
          if(response.code == 500){
            this.videoLoading = false
            this.$message.error(response.message)
          }else{
            this.videoLoading = false
            this.bannerImageList = []
            this.bannervideoUrl = fileList[fileList.length - 1].response.data.filePath
            this.$forceUpdate()
          }
        },
         beforeImageUpload(file){
          return new Promise((resolve, reject) => {
            if(file.type.split('/')[0] == 'image'){
              this.limitFileWH(750, 450, file).then(res=>{
                console.log(res)
                 if(res){
                  resolve() 
                 }else{
                  reject() 
                 }
              })
            }else{
              this.$message.error('请上传正常格式的图片！')
              reject()
            }
          })
            
        },
        beforeVideoUpload(){
           this.videoLoading = true
        },
        bannerUpLoadRemove(file, fileList){
          this.bannerImageList = fileList
        },
        resetList(){
          this.listParsem = {page:1,size:10}
          this.initGetList()
        },
        handleCurrentChange(val) {
          this.listParsem.page = val;
          this.initGetList()
        },
        sizechange(val) {
          this.listParsem.size = val;
          this.initGetList()
        },
        handleClose(){
            this.bannerImageList = []
            this.constructVisible = false
        },
        deleteBanner(v){
            this.constructForm = JSON.parse(JSON.stringify(v))
            this.bannervideoUrl = ''
            this.bannerImageList = []
            if(v.bannerType == 'mp4' || v.bannerType == 'avi'){
              this.bannervideoUrl = this.constructForm.bannerUrlList
            }else{
               this.constructForm.bannerUrlList.split(',').forEach(item=>{
               this.bannerImageList.push({name:'',url:item})
               })
            }
            this.constructVisible = true
        },
       async redCardsClose(v){
          const res = await bindActivity({id:v.id,bindFlag:0})
          if(res.code == '200'){
                this.synVisible = false
                this.$message.success('解绑成功！')
                this.initGetList()  
          }else{
                this.synVisible = false
                this.$message.error(res.message)
                this.initGetList()  
          }
        },
      
        redCardsBanner(v){
          // console.log()
          this.systemFrom.id = v.id
          this.systemFrom.bindFlag = 1
          this.systemFrom.plantActivityId = ''
          this.systemFrom.name = ''
          this.synVisible = true
        },
        limitFileWH(E_width, E_height, file) {
      const _this = this
      let imgWidth = ''
      let imgHight = ''
      const isSize = new Promise(function(resolve, reject) {
        const width = E_width
        const height = E_height
        const _URL = window.URL || window.webkitURL
        const img = new Image()
        img.onload = function() {
          imgWidth = img.width
          imgHight = img.height
          const valid = img.width === width && img.height === height
          valid ? resolve() : reject()
        }
        img.src = _URL.createObjectURL(file)
      }).then(() => {
        return true
      }, () => {
        _this.$message.error( '上传图片的尺寸应为' + E_width + '*' + E_height + '，当前上传图片的尺寸为：' + imgWidth + '*' + imgHight)
        return false
      })
      // new Promise((resolve, reject) => {
        
      // })
      return isSize
    },
        tableHeaderColor({ row, column, rowIndex, columnIndex }) {
          if (rowIndex === 0) {
            return "background-color: #F0F0F0;font-weight: 500;font-size:14px;color:#000;";
          }
       }
    }
}
</script>
<style scoped>
.center{
    width: 100%;
    height: calc(100% - 30px);
    background-color: #fff;
    padding-top: 30px;
}
.center-form{
  padding: 0 22px;
}
.center-construct{
    width: 100%;
    display: flex;
    justify-content: end;
    margin-bottom: 30px;
}
.avatar{
  width: 160px;
  height: 160px;
}
::v-deep .el-upload--text{
    width: 160px;
    height: 160px;
    line-height: 160px;
}

.center-table{
    margin-top: 30px;
    padding: 0 20px;
}
::v-deep .el-loading-mask{
 width: 160px !important;
 height: 160px !important;
}
</style>